<?php

namespace app\index\model;

use think\facade\Db;

class Contentmodel extends Commonmodel {

    protected $tagTable;
    protected $catTable;
    protected $detailTable;

    public function __construct(array $data = [])
    {
        $this->table = 'zhjs_content';
        $this->pk = 'id';
        parent::__construct($data);
        $this->tagTable = 'zhjs_content_tags';
        $this->detailTable = 'zhjs_content_detail';
        $this->catTable = 'zhjs_content_classify';
    }

    public function findAll($where = null, $pageParam = null, $num = 5){
        $whereData = [['a.is_delete' , '=', 1], ['a.type', '=', 1]];
        $paginate = ['list_rows'=>$num];

        if($where)  $whereData = array_merge($where, $whereData);
        if($pageParam = array_splice($pageParam, 1))  $paginate = array_merge($paginate, ['query'=>$pageParam]);

        $data = self::db()
            ->alias('a')
            ->leftJoin([$this->catTable=>'c'],'a.cid=c.id and c.is_delete and c.status = 1')
            ->field('a.id, a.title, a.desc, a.img, left(a.create_date, 10) as create_date, a.likes, c.name, a.comments, a.pageview, a.tags')
            ->where($whereData)
            ->order(['a.id'=>'desc'])
            ->paginate($paginate);

        if(!$data)  return false;

        $list['page'] = $data->render();
        $dataArr = $data->toArray();
        $list['data'] = $dataArr['data'];

        return $list;
    }

    /**
     * 查询文章内容
     * @param string $select
     * @param null $id
     * @param bool $is_detail
     * @param null $where
     * @return bool
     */
    public function findDetaiById($select=  "*", $id = null, $is_detail = true, $where = null){
        if(!$id)  return false;

        if($is_detail){
            $otherTbale = $this->detailTable;
        }else{
            $otherTbale = $this->videoTable;
        }
        $select = 'o.*, c.*, cf.name as cname';

        $where = $where ? array_merge($where, ['c.id'=>$id]) : ['c.id'=>$id];
        $info = self::db()
            ->alias('c')
            ->leftJoin([$otherTbale=>'o'],'o.id=c.id')
            ->leftJoin([$this->catTable=>'cf'], 'c.lid=cf.id')
            ->field($select)
            ->where($where)
            ->find();

        $info = $info ? $info->toArray() : '';

        if(!$info)  return false;
        return $info;
    }

    public function setPageviewById($id){
        if(!$id)  return false;

        return self::db()->where(['id'=>$id])->inc('pageview', 1)->update();
    }

    public function getTags($select = '*', $where = null){
        $whereArr = [['is_delete', '=', 1], ['status', '=', 1], ['examine_status', '=', 9]];
        if($where)  $whereArr = array_merge($where, $whereArr);
        $dataObj = Db::table($this->tagTable)->field($select)->where($whereArr)->order(['id'=>'desc'])->select();

        if(!$dataObj)  return false;
        return $dataObj->toArray();
    }

}

?>